package com.mew.chess.core.game.qmcs.game.common;

import com.mew.chess.core.common.handler.ChessPushMessageUtil;
import com.mew.chess.core.game.qmcs.game.QmcsRoomManager;
import com.mew.chess.core.game.qmcs.game.QmcsSeatManager;
import com.mew.chess.core.game.qmcs.game.QmcsTableManager;

import com.mew.chess.core.game.qmcs.game.message.PlayerEnterPushMessage;
import com.mew.chess.core.game.qmcs.game.message.PlayerExitPushMessage;
import com.mew.chess.core.game.qmcs.game.message.QmcsCMDMapType;
import com.mew.common.rest.bo.GameSession;
import com.mew.common.util.NumberUtil;
import com.zebra.common.ZebraBaseMessage;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.concurrent.Semaphore;
import java.util.stream.Collectors;


@Slf4j
public class QmcsTableUtil {
    public static void buildTable(QmcsRoomManager room, int tableSize){
        int alreadySize = room.getTableSize();
        int buildAfterSize = alreadySize + tableSize +1;
        for (int i = alreadySize +1; i<buildAfterSize; i++){
            room.pushTable(new QmcsTableManager(room.getRoomId(), room.getRoomType(),i));
        }
    }

    public static QmcsSeatManager sitDown(Integer seatNo, QmcsTableManager table, long userId, Semaphore semaphore){
        try {
            semaphore.acquire();
            List<Integer> emptySeat =  table.emptyPlayerSeat();
            if (emptySeat.isEmpty()){
                return null;
            }

            if (!emptySeat.contains(seatNo)){
                return null;
            }

            QmcsSeatManager seat = QmcsSeatManager.builder()
                    .tableId(table.getTableId())
                    .seatNo(seatNo)
                    .userId(userId)
                    .seatTime(System.currentTimeMillis())
                    .build();
            table.sitDown(seat);
            log.info("Player seat：userId {}， seatInfo {}", userId, seat.toString());
            return seat;
        }catch (Exception e){
            log.error("Player seat Error：", e);
            return null;
        }finally {
            semaphore.release();
        }

    }


    public static void playerInoutMsg(QmcsTableManager table, QmcsSeatManager seat, int inOutType){
        if (inOutType == 1){
            PlayerEnterPushMessage responseMessage = PlayerEnterPushMessage.builder()
                    .enterPlayer(table.getOnlineUserMap().get(seat.getUserId()))
                    .build();
            sendMsgByTable(table, responseMessage, QmcsCMDMapType.PlayerEnterMessage.code(), seat.getUserId());
        }else {
            PlayerExitPushMessage responseMessage = PlayerExitPushMessage.builder()
                    .seatNo(seat.getSeatNo())
                    .build();
            sendMsgByTable(table, responseMessage, QmcsCMDMapType.PlayerExitMessage.code(), seat.getUserId());
        }

    }


    public static void sendMsgByTable(QmcsTableManager table, ZebraBaseMessage message, int cmd, long exceptUserId){

        List<GameSession> sessions = table.getOnlineUserMap().values().stream()
                .map(u -> !NumberUtil.isLtOne(exceptUserId) && exceptUserId == u.getUserId() ? null : u.getGameSession())
                .filter(s -> null != s).collect(Collectors.toList());

        if (null == sessions || sessions.isEmpty()){
            return;
        }

        sessions.stream().forEach(session ->   ChessPushMessageUtil.pushMessage(session,cmd,message) );
    }


    public static int computeRemainStep(long startTime){
        if (startTime == 0){
            return  0;
        }
        long diff = System.currentTimeMillis() -  startTime;
        if (diff < 1){
            return  0;
        }

        long step = diff / QmcsConstantValue.STEP_TIME;
        return   (int) (step);
    }



}
